﻿using B.S.DataBase.MyProject.ErrorCode;
using B.S.DataBase.MyProject.Domain;
using B.S.DataBase.MyProject.Infrastructure.Interface;
using B.S.DataBase.MyRead.API.DTOs;
using MediatR;
using System;
using AutoMapper;
using B.S.DataBase.MyRead.API.Appicant.Command;

namespace B.S.DataBase.MyRead.API.Appicant.CommandHandler
{
    public class MenuQueryCommendHandlers : IRequestHandler<MenuQueryCommends, APIResult<List<MenuDtos>>>
    {

        private readonly IBaseRepository<Menu> menusRep;
        private readonly IMapper mapper;

        public MenuQueryCommendHandlers(IBaseRepository<Menu> menusRep, IMapper mapper)
        {
            this.menusRep = menusRep;
            this.mapper = mapper;
        }

        /// <summary>
        /// 查询菜单--自查
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public Task<APIResult<List<MenuDtos>>> Handle(MenuQueryCommends request, CancellationToken cancellationToken)
        {
            APIResult<List<MenuDtos>> result = new APIResult<List<MenuDtos>>();
            result.Code = APIEnum.查询成功;
            result.Msg = APIEnum.查询成功.ToString();
            var menus = menusRep.GetAllAsync().Result;
            var list = from a in menus
                       join b in menus on a.ParentMenuId equals b.MenuID
                 into parentMenu
                       from b in parentMenu.DefaultIfEmpty()
                       select new MenuDtos
                       {
                           MenuID = a.MenuID,
                           MenuName = a.MenuName,
                           ParentMenuId = a.ParentMenuId,
                           ParentMenuName = a != null ? a.ParentMenuName : "无",
                           Url = a.Url,
                           CreateName = a.CreateName,
                           CreateTime = a.CreateTime,
                           UpdateName = a.UpdateName,
                           UpdateTime = a.UpdateTime,

                       };
            var data = mapper.Map<List<MenuDtos>>(list.ToList());
            result.data = data;
            return Task.FromResult(result);
        }
    }
}
